/**
 * 图书管理相关的JavaScript代码
 */

$(document).ready(function() {
    // 加载图书列表页面
    if ($("#book-table").length > 0 || $("#book-table-body").length > 0) {
        loadBooks();
        
        // 搜索功能
        $("#search-btn").click(function() {
            const searchType = $("#search-type").val();
            const searchValue = $("#search-input").val();
            loadBooks(searchType, searchValue);
        });
        
        // 回车搜索
        $("#search-input").keypress(function(e) {
            if (e.which == 13) {
                const searchType = $("#search-type").val();
                const searchValue = $(this).val();
                loadBooks(searchType, searchValue);
            }
        });
    }
    
    // 处理添加图书表单提交
    $("#book-form").submit(function(e) {
        e.preventDefault();
        saveBook();
    });
    
    // 加载编辑页面的图书信息
    if (window.location.href.indexOf("book_edit.html") > -1) {
        const urlParams = new URLSearchParams(window.location.search);
        const bookId = urlParams.get('id');
        if (bookId) {
            loadBookById(bookId);
        }
    }
});

/**
 * 加载图书列表
 */
function loadBooks(searchType, searchValue) {
    let target = $("#book-table tbody");
    if (target.length === 0) {
        target = $("#book-table-body");
    }
    
    // 显示加载指示器
    target.html("<tr><td colspan='10'>加载中...</td></tr>");
    
    // 准备查询参数
    let data = {};
    if (searchType && searchValue) {
        data[searchType] = searchValue;
    } else if (searchValue) {
        data.likeValue = searchValue;
    }
    
    // 分页参数
    const urlParams = new URLSearchParams(window.location.search);
    const pageNo = urlParams.get("pageNo");
    if (pageNo) {
        data.pageNo = pageNo;
    }
    
    // 发送AJAX请求获取图书列表
    let url = window.location.href.indexOf("book_page.html") > -1 ? 
        "list.book" : 
        "list.book";
    
    $.ajax({
        url: url,
        type: "GET",
        data: data,
        dataType: "json",
        success: function(response) {
           
            
            // 处理分页响应
            if (response.recordList) {
                renderBookTable(response.recordList);
                updatePagination(response);
                return;
            }
            
            // 处理常规响应
            if (response.data) {
                renderBookTable(response.data);
            } else if (response.books) {
                renderBookTable(response.books);
            } else if (Array.isArray(response)) {
                renderBookTable(response);
            } else {
                alert("获取图书列表失败：" + (response.message || "未知错误"));
            }
        },
        error: function(xhr, status, error) {
            alert("获取图书列表时发生错误：" + error);
            console.error(xhr.responseText);
        }
    });
}

/**
 * 根据ID加载图书信息
 */
function loadBookById(bookId) {
    $.ajax({
        url: "queryById.book",
        type: "GET",
        data: { id: bookId },
        dataType: "json",
        success: function(response) {
            console.log("获取图书详情响应:", response);
            // 检查响应中是否包含数据，无论success字段如何
            let bookData = null;
            if (response.data) {
                bookData = response.data;
            } else if (response.book) {
                bookData = response.book;
            } else if (!response.success && !response.message) {
                // 如果响应本身就是图书对象
                bookData = response;
            }
            
            if (bookData) {
                // 填充表单数据
                $("#id").val(bookData.id);
                $("#isbn").val(bookData.isbn);
                $("#title").val(bookData.title);
                $("#author").val(bookData.author);
                $("#publisher").val(bookData.publisher);
                $("#publish_date").val(formatDate(bookData.publishDate));
                $("#price").val(bookData.price);
                $("#category").val(bookData.category);
                $("#status").val(bookData.status);
            } else {
                alert("获取图书信息失败：" + (response.message || "未知错误"));
            }
        },
        error: function(xhr, status, error) {
            alert("获取图书信息时发生错误：" + error);
            console.error(xhr.responseText);
        }
    });
}

/**
 * 保存图书信息（添加或更新）
 */
function saveBook() {
    // 获取表单数据
    const bookData = {
        id: $("#id").val(),
        isbn: $("#isbn").val(),
        title: $("#title").val(),
        author: $("#author").val(),
        publisher: $("#publisher").val(),
        publishDate: $("#publish_date").val(),
        price: $("#price").val(),
        category: $("#category").val(),
        status: $("#status").val()
    };
    
    // 验证必填字段
    if (!bookData.isbn) {
        alert("请输入ISBN");
        return;
    }
    if (!bookData.title) {
        alert("请输入书名");
        return;
    }
    if (!bookData.author) {
        alert("请输入作者");
        return;
    }
    
    // 使用表单提交
    const form = $('<form></form>')
        .attr('method', 'post')
        .attr('action', 'addOrUpdate.book');
    
    // 添加表单字段
    for (const key in bookData) {
        if (bookData[key]) {
            $('<input />')
                .attr('type', 'hidden')
                .attr('name', key)
                .attr('value', bookData[key])
                .appendTo(form);
        }
    }
    
    // 添加返回页面
    $('<input />')
        .attr('type', 'hidden')
        .attr('name', 'returnPage')
        .attr('value', 'book_page.html')
        .appendTo(form);
    
    // 将表单添加到页面并提交
    form.appendTo('body').submit();
}

/**
 * 删除图书
 */
function deleteBook(id) {
    if (confirm("确定要删除这本图书吗？")) {
        // 直接跳转到删除页面
        window.location.href = "deleteById.book?id=" + id;
    }
}

/**
 * 编辑图书
 */
function editBook(id) {
    // 设置编辑标记到会话
    // 跳转到编辑页面
    window.location.href = "toEdit.book?id=" + id;
}

/**
 * 渲染图书表格
 */
function renderBookTable(books) {
    let target = $("#book-table tbody");
    if (target.length === 0) {
        target = $("#book-table-body");
    }
    
    if (!books || books.length === 0) {
        target.html("<tr><td colspan='10'>暂无图书数据</td></tr>");
        return;
    }
    
    let html = "";
    
    // 遍历图书数据构建表格行
    for (let i = 0; i < books.length; i++) {
        const book = books[i];
        html += `<tr>
            <td>${book.id}</td>
            <td>${book.isbn || ''}</td>
            <td>${book.title || ''}</td>
            <td>${book.author || ''}</td>
            <td>${book.publisher || ''}</td>
            <td>${formatDate(book.publishDate) || ''}</td>
            <td>${book.price ? '¥' + book.price : ''}</td>
            <td>${book.category || ''}</td>
            <td>${book.status || ''}</td>
            <td>
                <a href="toEdit.book?id=${book.id}" class="btn-small">编辑</a>
                <button class="btn-small btn-danger" onclick="deleteBook(${book.id})">删除</button>
                ${book.status === '在库' ? `<button class="btn-small btn-primary" onclick="showBorrowDialog(${book.id})">借阅</button>` : ''}
            </td>
        </tr>`;
    }
    
    // 更新表格内容
    target.html(html);
}

/**
 * 更新分页控件
 */
function updatePagination(data) {
    // 更新分页信息
    $("#likeValueStr").val(data.likeValue);
    $("#recordCount").text(data.recordCount);
    $("#totalPages").text(data.totalPages);
    $("#pageNo").text(data.pageNo);
    
    // 更新分页链接
    $("#homePage").attr("href", "book_page.html?pageNo=1&likeValue=" + data.likeValue);
    
    if (parseInt(data.pageNo) > 1) {
        $("#prevPage").attr("href", "book_page.html?pageNo=" + (parseInt(data.pageNo) - 1) + "&likeValue=" + data.likeValue);
        $("#prevPage").removeClass("disabled");
    } else {
        $("#prevPage").attr("href", "javascript:void(0)");
        $("#prevPage").addClass("disabled");
    }
    
    if (parseInt(data.pageNo) < parseInt(data.totalPages)) {
        $("#nextPage").attr("href", "book_page.html?pageNo=" + (parseInt(data.pageNo) + 1) + "&likeValue=" + data.likeValue);
        $("#nextPage").removeClass("disabled");
    } else {
        $("#nextPage").attr("href", "javascript:void(0)");
        $("#nextPage").addClass("disabled");
    }
    
    $("#lastPage").attr("href", "book_page.html?pageNo=" + data.totalPages + "&likeValue=" + data.likeValue);
}

/**
 * 显示借阅对话框
 */
function showBorrowDialog(bookId) {
    // 跳转到借阅页面并传递图书ID
    window.location.href = "/librarymanagementsystem/borrow_add.html?bookId=" + bookId;
}

/**
 * 格式化日期
 */
function formatDate(dateValue) {
    // 如果为空，返回空字符串
    if (!dateValue) {
        return '';
    }
    
    let date;
    
    // 如果是毫秒级时间戳（数字或数字字符串）
    if (!isNaN(dateValue) && (typeof dateValue === 'number' || !isNaN(parseInt(dateValue)))) {
        // 如果是数字字符串，先转为数字
        const timestamp = typeof dateValue === 'number' ? dateValue : parseInt(dateValue);
        date = new Date(timestamp);
    } else {
        // 否则尝试直接创建日期对象
        date = new Date(dateValue);
    }
    
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
        console.error("无效的日期值:", dateValue);
        return dateValue; // 无法解析则返回原值
    }
    
    // 格式化为YYYY-MM-DD
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    
    return `${year}-${month}-${day}`;
} 